package avicit.im.lantop.archiveplanmanager.archiveplanedit.action;

import avicit.cbb.appreg.service.CommSysInfoIntfsService;
import avicit.im.lantop.archiveplanmanager.archiveplanedit.domain.AjaxResult;
import avicit.im.lantop.archiveplanmanager.archiveplanedit.domain.ArchivePlan;
import avicit.im.lantop.archiveplanmanager.archiveplanedit.domain.ArchivePlanTree;
import avicit.im.lantop.archiveplanmanager.archiveplanedit.service.ArchivePlanService;
import avicit.im.lantop.archiveplanmanager.archiveplanedit.service.api.ArchivePlanServiceApi;
import avicit.im.lantop.docmanager.deptdocmanager.service.DeptdocmanagerService;
import avicit.im.lantop.docmanager.mydocmanager.domain.LantopSubmit;
import avicit.platform6.api.session.SessionHelper;
import avicit.platform6.api.sysuser.SysDeptAPI;
import avicit.platform6.api.sysuser.SysOrgAPI;
import avicit.platform6.api.sysuser.SysRoleAPI;
import avicit.platform6.api.sysuser.SysUserAPI;
import avicit.platform6.api.sysuser.dto.SysOrg;
import avicit.platform6.api.sysuser.dto.SysUser;
import avicit.platform6.api.sysuser.impl.SysDeptAPImpl;
import avicit.platform6.api.sysuser.impl.SysUserAPImpl;
import avicit.platform6.bpm.web.service.BpmOperateService;
import avicit.platform6.commons.utils.web.TreeNode;
import avicit.platform6.core.context.ThreadContextHelper;
import avicit.platform6.core.jdbc.JdbcAvicit;
import avicit.platform6.core.properties.PlatformConstant;
import avicit.platform6.core.spring.SpringFactory;
import avicit.platform6.modules.system.archiveManagerHome.service.ArchiveManagerHomeService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 档案归档计划controller
 *
 * @author xmw
 */
@Controller
@RequestMapping("/ArchivePlanController")
@SuppressWarnings("deprecation")
public class ArchivePlanController {

    @Resource
    private CommSysInfoIntfsService commSysInfoIntfsService; // 获取系统ID

    @Autowired
    private ArchivePlanServiceApi archivePlanService;

    @Autowired
    private DeptdocmanagerService deptdocmanagerService;

    @Autowired
    private SysOrgAPI sysOrgAPI;

    @Autowired
    private ArchiveManagerHomeService archiveManagerHomeService;


    @Autowired
    private JdbcAvicit jdbcAvicit;

    private SysUserAPI userLoader = SpringFactory.getBean(SysUserAPImpl.class);

    private SysDeptAPI deptLoader = SpringFactory.getBean(SysDeptAPImpl.class);

    private SysRoleAPI roleLoader = SpringFactory.getBean(SysRoleAPI.class);

    private String sysId = "";


    @RequestMapping("/toPageByRole")
    public ModelAndView getPlanNode(HttpServletRequest request) throws Exception {
        ModelAndView mav = new ModelAndView();
        SysUser loginSysUser = SessionHelper.getLoginSysUser(request);
        String orgIdentity = SessionHelper.getCurrentOrgIdentity(request);
        SysOrg so = sysOrgAPI.getSysOrgBySysOrgId(orgIdentity);
        String orgCode = so.getOrgCode();
        Integer isfulltime = 1;
        Integer isParttime = 1;
        //获取专职档案角色信息
        String fulltimeCode = orgCode + "_Sanxia_Manager_ROLE";
        //根据兼职档案角色信息
        String parttimeCode = orgCode + "_Parttime_Manager_ROLE";

        List<Map<String, Object>> roleCodeByUserIdAndOrgId = archiveManagerHomeService.getRoleCodeByUserIdAndOrgId(loginSysUser.getId(), orgIdentity);

        if (roleCodeByUserIdAndOrgId != null && roleCodeByUserIdAndOrgId.size() > 0) {
            for (Map<String, Object> stringObjectMap : roleCodeByUserIdAndOrgId) {
                if (fulltimeCode.equals(stringObjectMap.get("ROLE_CODE"))) {
                    isfulltime = 2;
                    break;
                }
            }
            for (Map<String, Object> stringObjectMap : roleCodeByUserIdAndOrgId) {
                if (parttimeCode.equals(stringObjectMap.get("ROLE_CODE"))) {
                    isParttime = 2;
                    break;
                }
            }
        }
        if ("1".equals(loginSysUser.getId())) {
            isfulltime = 2;
            isParttime = 2;
        }
        if (isfulltime == 1 && isParttime == 2) {

            mav.setViewName("avicit/im/lantop/archiveplanmanager/archiveplanedit/iframParttimePlanManage");
        } else {
            mav.setViewName("avicit/im/lantop/archiveplanmanager/archiveplanedit/ArchivePlanEditManage.jsp?sysId=LANTOP");
        }
//        mav.setViewName("avicit/im/lantop/archiveplanmanager/archiveplanedit/iframParttimePlanManage");
        return mav;
    }


    /**
     * 获取归档计划节点
     *
     * @param request
     * @return
     * @throws Exception
     */

//    @RequestMapping("/getPlanNode")
//    @ResponseBody
//    public List<Map<String, Object>> getPlanNode(HttpServletRequest request, String id) throws Exception {
//        String orgId = SessionHelper.getCurrentOrgId(request);
//        List<Map<String, Object>> planTreeNode = archivePlanService.getPlanTreeNode(orgId, id);
//        return planTreeNode;
//    }

    /**
     * 根据id获取父节点数据
     *
     * @param id 节点id
     * @return
     * @throws Exception
     */
    @RequestMapping("/findPNodeIdByNodeId")
    @ResponseBody
    public Map<String, Object> findPNodeIdByNodeId(String id) throws Exception {
//        Map<String, Object> pIdMap = archivePlanService.findPNodeIdByNodeId(id);
//        return pIdMap;
        return new HashMap<>();
    }

    /**
     * 修改计划节点
     *
     * @param
     * @return
     * @throws Exception
     */
//    @RequestMapping("/editPlanNode")
//    @ResponseBody
//    public AjaxResult editNodeIdByNodeId(ArchivePlanTree plantree) throws Exception {
//        archivePlanService.editNodeIdByNodeId(plantree);
//        return AjaxResult.ok();
//    }

    @RequestMapping("/getArchivePlanListNodeOpd")
    public ModelAndView getArchivePlanListNodeOpd(HttpServletRequest request) throws Exception {
        ModelAndView mav = new ModelAndView();
        try {
            //获取参数
            String nodeName = request.getParameter("nodeName");
            String orgId = SessionHelper.getCurrentOrgIdentity();
            //执行
//            mav = archivePlanService.getArchivePlanStatus(nodeName, orgId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mav;
    }

    /**
     * 删除节点
     *
     * @param
     * @return
     * @throws Exception
     */
//    @RequestMapping("/delPlanNode")
//    @ResponseBody
//    public AjaxResult delPlanNode(String ids) throws Exception {
//        Integer i = archivePlanService.delNodeIdByIds(ids);
//        return AjaxResult.ok(i);
//    }

    /**
     * 添加归档计划节点
     *
     * @param request
     * @return
     * @throws Exception
     */
//    @RequestMapping("/savePlanNode")
//    @ResponseBody
//    public AjaxResult addPlanNode(HttpServletRequest request, @RequestBody ArchivePlanTree plantree, String pid) throws Exception {
//        String deptId = SessionHelper.getCurrentDeptId(request);
//        String orgId = SessionHelper.getCurrentOrgId(request);
//        plantree.setDeptId(deptId);
//        plantree.setOrgId(orgId);
//        this.sysId = request.getParameter("sysId");
//        this.sysId = "LANTOP"; // 系统ID
//        archivePlanService.addPlanTreeNode(plantree);
//        return AjaxResult.ok();
//    }

    /**
     * 加载归档计划节点树
     *
     * @param planTree 计划节点对象
     * @return AjaxResult
     * @throws Exception
     * @throws
     * @author XMW
     */
//    @RequestMapping("/getArchivesPlanTree")
//    @ResponseBody
//    public AjaxResult getArchivesClassTree(HttpServletRequest request, ArchivePlanTree planTree) throws Exception {
//        ModelAndView mav = new ModelAndView();
//        mav.setView(null);
//        String orgId = ThreadContextHelper.getOrgId();
//        planTree.setOrgId(orgId);
//        List<TreeNode> nodesList = archivePlanService.getArchivePlanNodeTree(planTree);
//
//        return AjaxResult.ok(nodesList);
//    }

    /**
     * 到达数据显示页面
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/toDataJsp")
    public String toDataJsp(HttpServletRequest request, String id, String sysId, String flag, String fileNodeId, String fileIds) throws Exception {
        String isAn = request.getParameter("isAn");
        request.setAttribute("nodeId", id);
        request.setAttribute("sysId", sysId);
        SysUser loginSysUser = SessionHelper.getLoginSysUser(request);
        request.setAttribute("userId", loginSysUser.getId());
        request.setAttribute("userName", loginSysUser.getName());
        String orgIdentity = SessionHelper.getCurrentOrgIdentity(request);
        SysOrg so = sysOrgAPI.getSysOrgBySysOrgId(orgIdentity);
        String orgCode = so.getOrgCode();
        Integer isfulltime = 1;
        Integer isParttime = 1;
        //获取专职档案角色信息
        String fulltimeCode = orgCode + "_Sanxia_Manager_ROLE";
        //根据兼职档案角色信息
        String parttimeCode = orgCode + "_Parttime_Manager_ROLE";

//        List<Map<String, Object>> roleCodeByUserIdAndOrgId = archiveManagerHomeService.getRoleCodeByUserIdAndOrgId(loginSysUser.getId(), orgIdentity);

//        if (roleCodeByUserIdAndOrgId != null && roleCodeByUserIdAndOrgId.size() > 0) {
//            for (Map<String, Object> stringObjectMap : roleCodeByUserIdAndOrgId) {
//                if (fulltimeCode.equals(stringObjectMap.get("ROLE_CODE"))) {
//                    isfulltime = 2;
//                    break;
//                }
//            }
//            for (Map<String, Object> stringObjectMap : roleCodeByUserIdAndOrgId) {
//                if (parttimeCode.equals(stringObjectMap.get("ROLE_CODE"))) {
//                    isParttime = 2;
//                    break;
//                }
//            }
//        }
        if ("1".equals(loginSysUser.getId())) {
            isfulltime = 2;
            isParttime = 2;
        }

        String roleSql = "";
        if (isfulltime == 1 && isParttime == 2) {
            roleSql = " and status=2 ";
        }
        if (fileIds != null && !"".equals(fileIds)) {
            request.setAttribute("fileIds", fileIds);
        }

        if (fileNodeId != null && !"".equals(fileNodeId)) {
            request.setAttribute("fileNodeId", fileNodeId);
        }
        if (isAn != null && !"".equals(isAn)) {
            request.setAttribute("isAn", isAn);
        }

        request.setAttribute("roleSql", roleSql);
        request.setAttribute("isfulltime", isfulltime);
        request.setAttribute("isParttime", isParttime);
        request.setAttribute("flag", flag);
        return "avicit/im/lantop/archiveplanmanager/archiveplanedit/IframePlanLevelManage";
    }


    @RequestMapping("/isLastNode")
    @ResponseBody
    public Map<String, Object> isLastNode(HttpServletRequest request, String nodeId, String sysId) {
        Map<String, Object> resultMap = new HashMap<>();
        String orgId = SessionHelper.getCurrentOrgId(request);
//        Boolean nodeIsLastById = archivePlanService.findNodeIsLastById(nodeId, sysId, orgId);
//        if (nodeIsLastById) {
            resultMap.put("falg", 1);
//        } else {
            resultMap.put("falg", 2);
//        }
        return resultMap;
    }

    /**
     * 加载归档计划表格
     *
     * @param request
     * @return
     * @throws Exception
     */
//    @RequestMapping("/getPlanRecord")
//    @ResponseBody
//    public Map<String, Object> getPlanRecord(HttpServletRequest request, String nodeId, String sysId, Integer page, Integer rows, String whereSql, String roleSql) throws Exception {
//        String orgId = SessionHelper.getCurrentOrgId(request);
//        String flag = request.getParameter("flag");
//        // 查询该节点下的归档计划数据
//        StringBuffer sbsql = new StringBuffer();
//        if (whereSql != null && !"".equals(whereSql)) {
//            sbsql.append(" AND PLAN_NAME ");
//            sbsql.append(whereSql);
//        }
//        if ("1".equals(flag)) {
//            sbsql.append(" AND STATUS=2 ");
//        }
//
//        String orgIdentity = SessionHelper.getCurrentOrgIdentity(request);
//        SysUser loginSysUser = SessionHelper.getLoginSysUser(request);
//        SysOrg so = sysOrgAPI.getSysOrgBySysOrgId(orgIdentity);
//        String orgCode = so.getOrgCode();
//        Integer isfulltime = 1;
//        Integer isParttime = 1;
//        //获取专职档案角色信息
//        String fulltimeCode = orgCode + "_Sanxia_Manager_ROLE";
//        //根据兼职档案角色信息
//        String parttimeCode = orgCode + "_Parttime_Manager_ROLE";
//
//        List<Map<String, Object>> roleCodeByUserIdAndOrgId = archiveManagerHomeService.getRoleCodeByUserIdAndOrgId(loginSysUser.getId(), orgIdentity);
//
//        if (roleCodeByUserIdAndOrgId != null && roleCodeByUserIdAndOrgId.size() > 0) {
//            for (Map<String, Object> stringObjectMap : roleCodeByUserIdAndOrgId) {
//                if (fulltimeCode.equals(stringObjectMap.get("ROLE_CODE"))) {
//                    isfulltime = 2;
//                    break;
//                }
//            }
//            for (Map<String, Object> stringObjectMap : roleCodeByUserIdAndOrgId) {
//                if (parttimeCode.equals(stringObjectMap.get("ROLE_CODE"))) {
//                    isParttime = 2;
//                    break;
//                }
//            }
//        }
//        if ("1".equals(loginSysUser.getId())) {
//            isfulltime = 2;
//            isParttime = 2;
//        }
//
//        if (isfulltime == 1 && isParttime == 2) {
//            sbsql.append(" AND (select count(0) from LANTOP_ARCHIVE_PLAN_ITEM T1 where T.id=t1.plan_id and is_del=1 and ORG_ID='" + orgId + "')>0 ");
//        }
//
//
//        Map<String, Object> planData = archivePlanService.getPlanByNoid(nodeId, sysId, orgId, page, rows, sbsql.toString(), roleSql);
//        return planData;
//    }

    /**
     * 添加和编辑归档计划计划
     *
     * @param param
     * @return
     * @throws Exception
     */
    @RequestMapping("/saveAndEditArchivePlan")
    @ResponseBody
    public ModelAndView saveArchivePlan(HttpServletRequest request, @RequestBody Map<String, Object> param) throws Exception {
        ModelAndView mav = new ModelAndView();
        try {
            String orgId = SessionHelper.getCurrentOrgId(request);
            param.put("orgId", orgId);

            //计划名称不能为空
            if (param.get("PLAN_NAME") == null || param.get("PLAN_NAME") == "" || param.get("PLAN_NAME") == "null") {
                mav.addObject("flag", 3);
                return mav;
            }
            String operationType = param.get("operationType") == null ? "" : param.get("operationType").toString();
            //判断计划名称是否重复
//            if (!"edit".equals(operationType)) {
//                List<Map<String, Object>> list = archivePlanService.findArchivePlan();
//                for (Map<String, Object> map : list) {
//                    if (map.get("PLAN_NAME") != null && map.get("PLAN_NAME") != "") {
//                        if (map.get("PLAN_NAME").toString().equals(param.get("PLAN_NAME").toString())) {
//                            mav.addObject("flag", "2");
//                            return mav;
//                        }
//                    }
//                }
//            }
//            archivePlanService.saveArchivePlan(param);
            mav.addObject("flag", "0");
        } catch (Exception e) {
            mav.addObject("flag", "1");
            e.printStackTrace();
        }
        return mav;
    }

    /**
     * 添加计划项目
     *
     * @param request
     * @return
     * @throws Exception
     */
//    @RequestMapping("/saveArchivePlanItem")
//    @ResponseBody
//    public AjaxResult saveArchivePlanItem(HttpServletRequest request, @RequestBody
//            Map<String, Object> param) throws Exception {
//        String orgId = SessionHelper.getCurrentOrgId(request);
//        param.put("orgId", orgId);
//        param.put("qzh", orgId);
//        // 查询该节点下的归档计划数据
//        archivePlanService.saveArchivePlanItem(param);
//        return AjaxResult.ok();
//    }

    /**
     * 编辑计划的项目
     *
     * @param request
     * @return
     * @throws Exception
     */
//    @RequestMapping("/editArchivePlanItem")
//    @ResponseBody
//    public AjaxResult editArchivePlanItem(HttpServletRequest request, @RequestBody
//            Map<String, Object> param) throws Exception {
//        // 查询该节点下的归档计划数据
//        int i = archivePlanService.editArchivePlanItem(param);
//        return AjaxResult.ok(i);
//    }


    @RequestMapping("/getParttimrPlan")
    @ResponseBody
    public Map<String, Object> getParttimrPlan(HttpServletRequest request) throws Exception {
        Map<String, Object> result = new HashMap<>();
        SysUser loginSysUser = SessionHelper.getLoginSysUser(request);
        String orgId = SessionHelper.getCurrentOrgId(request);
        String whereSql = request.getParameter("whereSql");
        String falg = request.getParameter("falg");
        Long page = request.getParameter("page") == null ? 1 : Long.parseLong(request.getParameter("page"));
        Long rows = request.getParameter("rows") == null ? 20 : Long.parseLong(request.getParameter("rows"));
//        String rows = request.getParameter("rows");
        StringBuffer sbsql = new StringBuffer();
        if (whereSql != null && !"".equals(whereSql)) {
            sbsql.append(" AND ITEM_NAME ");
            sbsql.append(whereSql);
        }

        if ("1".equals(falg)) {
            sbsql.append(" AND STATUS=1 ");
        }

        sbsql.append(" AND DUTY_USER_ID='" + loginSysUser.getId() + "' ");
        sbsql.append(" AND ( SELECT STATUS FROM LANTOP_ARCHIVE_PLAN WHERE ID = T.PLAN_ID )<>1 ");


        Long total = this.jdbcAvicit.getJdbcTemplate().queryForObject("SELECT COUNT(1) FROM LANTOP_ARCHIVE_PLAN_ITEM T WHERE IS_DEL=1 AND ORG_ID='" + orgId + "' AND SYS_ID='LANTOP' " + sbsql.toString(),Long.class);
        result.put("total", total);

        List<Map<String, Object>> mapList = jdbcAvicit.getJdbcTemplate().queryForList("SELECT\n" +
                "\t* \n" +
                "FROM\n" +
                "\t(\n" +
                "\tSELECT\n" +
                "\t\tROW_.*,\n" +
                "\t\tROWNUM ROWNUM_ \n" +
                "\tFROM\n" +
                "(\n" +
                "\t\tSELECT\n" +
                "\t\t\tT2.* \n" +
                "\t\tFROM\n" +
                "\t\t\t(" +
                "\t\tSELECT\n" +

                "\t\t\t( SELECT PLAN_NAME FROM LANTOP_ARCHIVE_PLAN WHERE ID = T.PLAN_ID ) PLAN_NAME,\n" +
                "\t\t\t( SELECT ARCHIVE_DATE FROM LANTOP_ARCHIVE_PLAN WHERE ID = T.PLAN_ID ) ARCHIVE_DATE1,\n" +
                "\t\t\t( SELECT NODE_ID FROM LANTOP_ARCHIVE_PLAN WHERE ID = T.PLAN_ID ) NODE_ID,\n" +
                "\t\t\tT.* \n" +
                "\t\tFROM\n" +
                "\t\t\tLANTOP_ARCHIVE_PLAN_ITEM T \n" +
                "\t\tWHERE\n" +
                "\t\t\tIS_DEL = 1 \n" +
                "\t\t\tAND ORG_ID = '" + orgId + "' \n" +
                "\t\t\tAND SYS_ID = 'LANTOP' \n" +
                "\t\t  " + sbsql.toString() + " " +
                "\t) T2 \n" +
                "\t\tORDER BY\n" +
                "\t\t\tT2.STATUS ASC,\n" +
                "\t\t\tt2.ARCHIVE_DATE1 ASC,\n" +
                "\t\t\tt2.PLAN_NAME,\n" +
                "\t\t\tt2.ITEM_NAME " +
                ") ROW_ \n" +
                "\tWHERE\n" +
                "\t\tROWNUM < " + (page * rows + 1) + " \n" +
                "\t) \n" +
                "WHERE\n" +
                "\tROWNUM_ >" + ((page - 1) * rows));
        /*if (mapList != null && mapList.size() > 0) {
            for (Map<String, Object> map : mapList) {
                List<Map<String, Object>> mapList1 = jdbcAvicit.getJdbcTemplate().queryForList("SELECT\n" +
                        "\t\tLISTAGG ( NODE_NAME, '-' ) within GROUP ( ORDER BY NODE_NAME ) AS NODE_NAME \n" +
                        "\tFROM\n" +
                        "\t\t( SELECT NODE_NAME FROM LANTOP_ARCHIVE_PLAN_TREE START WITH ID = '" + map.get("NODE_ID") + "' CONNECT BY PRIOR PID = ID )");
                if (mapList1!=null&&mapList1.size()>0){
                    Object node_name = mapList1.get(0).get("NODE_NAME");
                    map.put("NODE_NAME",node_name);
                }
            }
        }*/
        result.put("rows",mapList);
        return result;
    }


    /**
     * 根据计划id获取其下项目信息
     *
     * @param request
     * @return
     * @throws Exception
     */
//    @RequestMapping("/getTaskReocrdByPlanId")
//    @ResponseBody
//    public Map<String, Object> getTaskReocrdByPlanId(HttpServletRequest request, String planId, String sysId, Integer page, Integer rows, String whereSql) throws Exception {
//        String orgId = SessionHelper.getCurrentOrgId(request);
//        String flag = request.getParameter("flag");
//        SysUser loginSysUser = SessionHelper.getLoginSysUser(request);
//        String orgIdentity = SessionHelper.getCurrentOrgIdentity(request);
//        SysOrg so = sysOrgAPI.getSysOrgBySysOrgId(orgIdentity);
//        String orgCode = so.getOrgCode();
//        Integer isfulltime = 1;
//        Integer isParttime = 1;
//        //获取专职档案角色信息
//        String fulltimeCode = orgCode + "_Sanxia_Manager_ROLE";
//        //根据兼职档案角色信息
//        String parttimeCode = orgCode + "_Parttime_Manager_ROLE";
//
//        List<Map<String, Object>> roleCodeByUserIdAndOrgId = archiveManagerHomeService.getRoleCodeByUserIdAndOrgId(loginSysUser.getId(), orgIdentity);
//
//        if (roleCodeByUserIdAndOrgId != null && roleCodeByUserIdAndOrgId.size() > 0) {
//            for (Map<String, Object> stringObjectMap : roleCodeByUserIdAndOrgId) {
//                if (fulltimeCode.equals(stringObjectMap.get("ROLE_CODE"))) {
//                    isfulltime = 2;
//                    break;
//                }
//            }
//            for (Map<String, Object> stringObjectMap : roleCodeByUserIdAndOrgId) {
//                if (parttimeCode.equals(stringObjectMap.get("ROLE_CODE"))) {
//                    isParttime = 2;
//                    break;
//                }
//            }
//        }
//        if ("1".equals(loginSysUser.getId())) {
//            isfulltime = 2;
//            isParttime = 2;
//        }
//
//        String roleSql = "";
//        StringBuffer sbsql = new StringBuffer();
//        if (whereSql != null && !"".equals(whereSql)) {
//            sbsql.append(" AND ITEM_NAME ");
//            sbsql.append(whereSql);
//        }
//        if (isfulltime == 1 && isParttime == 2) {
//            sbsql.append(" AND DUTY_USER_ID='" + loginSysUser.getId() + "' ");
//        }
//
//        if ("1".equals(flag)) {
//            sbsql.append(" AND STATUS=1 ");
//        }
//
//        Map<String, Object> planData = archivePlanService.getTaskReocrdByPlanId(planId, sysId, orgId, page, rows, sbsql.toString());
//
//        return planData;
//    }

    /**
     * 删除任务
     *
     * @param request
     * @throws Exception
     * @throws
     * @author xmw
     */
//    @RequestMapping("/delTask")
//    @ResponseBody
//    public AjaxResult delTask(HttpServletRequest request, String ids) throws Exception {
//        int i = archivePlanService.delTaskByIds(ids);
//        return AjaxResult.ok(i);
//    }

    /**
     * 删除计划
     *
     * @param request
     * @throws Exception
     * @throws
     * @author xmw
     */
//    @RequestMapping("/delPlan")
//    @ResponseBody
//    public AjaxResult delPlan(HttpServletRequest request, String ids) throws Exception {
//        int i = archivePlanService.delPlanByIds(ids);
//        return AjaxResult.ok(i);
//    }


    /**
     * 发布计划
     *
     * @param request
     * @throws Exception
     * @throws
     * @author xmw
     */
//    @RequestMapping("/publishPlan")
//    @ResponseBody
//    public AjaxResult publishPlanByIds(HttpServletRequest request, String ids) throws Exception {
//        SysUser loginSysUser = SessionHelper.getLoginSysUser(request);
//        int i = archivePlanService.publishPlan(ids, loginSysUser.getId(), loginSysUser.getName());
//        return AjaxResult.ok(i);
//    }


    /**
     * 取消发布计划
     *
     * @param request
     * @throws Exception
     * @throws
     * @author xmw
     */
//    @RequestMapping("/unpublishPlan")
//    @ResponseBody
//    public AjaxResult unpublishPlanByIds(HttpServletRequest request, String ids) throws Exception {
//        String s = ids.replaceAll(",", "','");
//        List<Map<String, Object>> mapList = jdbcAvicit.getJdbcTemplate().queryForList("SELECT * FROM LANTOP_ARCHIVE_PLAN_ITEM WHERE PLAN_ID IN ('" + s + "') AND IS_DEL=1 AND (STATUS=2 OR STATUS=3)");
//        if (mapList != null && mapList.size() > 0) {
//            return AjaxResult.ok(-1);
//        }
//        List<Map<String, Object>> mapList1 = jdbcAvicit.getJdbcTemplate().queryForList("SELECT * FROM LANTOP_ARCHIVE_PLAN_ITEM WHERE PLAN_ID IN ('" + s + "') AND IS_DEL=1 AND STATUS=1");
//        if (mapList1 != null && mapList1.size() > 0) {
//            for (Map<String, Object> map : mapList1) {
//                if (map.get("ATTRIBUTE_04") != null && !"".equals(map.get("ATTRIBUTE_04").toString())) {
//                    return AjaxResult.ok(-2);
//                }
//            }
//        }
//        int i = jdbcAvicit.getJdbcTemplate().update(" UPDATE LANTOP_ARCHIVE_PLAN SET STATUS=1,PUBLISH_USER_ID='',PUBLISH_USER='',PUBLISH_DATE=NULL WHERE ID IN ('" + s + "') ");
//        return AjaxResult.ok(i);
//    }

    /**
     * 设置计划项目已归档
     *
     * @param request
     * @throws
     * @author xmw
     */
//    @RequestMapping("/setTaskArchiveStatus")
//    @ResponseBody
//    public AjaxResult setTaskArchiveStatus(HttpServletRequest request, String ids) throws Exception {
//        String orgCode = request.getParameter("orgCode");
//        if (orgCode.length() > 16) {
//            orgCode = orgCode.substring(orgCode.length() - 16);
//        }
//        String s = ids.replaceAll(";", "','");
//        List<Map<String, Object>> mapList = jdbcAvicit.getJdbcTemplate().queryForList("SELECT * FROM LANTOP_ARCHIVE_PLAN_ITEM WHERE ID in ('" + s + "')");
//        if (mapList != null && mapList.size() > 0) {
//            Object attribute_04 = mapList.get(0).get("ATTRIBUTE_04");
//            String recdIds = attribute_04 == null ? "" : attribute_04.toString();
//            Map<String, String> map = null;
//            if (!"".equals(recdIds)) {
//                map = JSON.parseObject(recdIds, Map.class);
//            }
//            if (map != null && map.size() > 0) {
//                for (String s1 : map.keySet()) {
//                    String s2 = map.get(s1);
//                    if (!"".equals(s2)) {
//                        String s3 = s2.replaceAll(";", "','");
//                        List<Map<String, Object>> mapList1 = jdbcAvicit.getJdbcTemplate().queryForList("SELECT LANTOP_ARCHIVE_STATUS FROM LANTOP_DATA_V_" + orgCode + " WHERE LANTOP_RCD_ID IN ('" + s3 + "')");
//                        if (mapList1 != null && mapList1.size() > 0) {
//                            for (Map<String, Object> stringObjectMap : mapList1) {
//                                if (!"3".equals(stringObjectMap.get("LANTOP_ARCHIVE_STATUS"))) {
//                                    return AjaxResult.ok(-2);
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        }
//        int i = archivePlanService.setTaskStatus(ids);
//        return AjaxResult.ok(i);
//    }


    /**
     * 根据计划id获取归档率
     *
     * @param
     * @throws
     * @author xmw
     */
    /*@RequestMapping("/refreshPlanRow")
    @ResponseBody
    public AjaxResult refreshPlanRow(String planId) throws Exception {
        Map<String, Object> resultMap = archivePlanService.refreshPlanRow(planId);
        return AjaxResult.ok(resultMap);
    }*/


    /**
     * 加载模板数据
     *
     * @param request
     * @throws
     * @author xmw
     */
//    @RequestMapping("/getTemplate")
//    @ResponseBody
//    public List<Map<String, Object>> getTemplate(HttpServletRequest request) throws Exception {
//        String orgId = SessionHelper.getCurrentOrgId(request);
//        String sysId = request.getParameter("sysId");
//        List<Map<String, Object>> resultMap = archivePlanService.getTemplate(orgId, sysId);
//        return resultMap;
//    }


    /**
     * 根据模板查询其下的项目
     *
     * @param request
     * @throws
     * @author xmw
     */
//    @RequestMapping("/getTemplateTask")
//    @ResponseBody
//    public Map<String, Object> getTemplateTask(HttpServletRequest request, String id, Integer page, Integer rows) throws Exception {
//        String orgId = SessionHelper.getCurrentOrgId(request);
//        String sysId = request.getParameter("sysId");
//        Map<String, Object> resultMap = archivePlanService.getTemplateTask(orgId, sysId, id, page, rows);
//        return resultMap;
//    }


    /**
     * 给项目设置模板
     *
     * @param
     * @throws
     * @author xmw
     */
//    @RequestMapping("/setTaskTemplate")
//    @ResponseBody
//    public AjaxResult setTaskTemplate(HttpServletRequest request, String planId, String modelId, String sysId) throws Exception {
//        String orgId = SessionHelper.getCurrentOrgId(request);
//        archivePlanService.setTaskTemplate(orgId, sysId, planId, modelId);
//        return AjaxResult.ok();
//    }


    /**
     * 设置归档计划完结
     *
     * @param
     * @throws
     * @author xmw
     */
//    @RequestMapping("/setTaskArchiveEnd")
//    @ResponseBody
//    public Map<String, Object> setTaskArchiveEnd(HttpServletRequest request, String taskIds, String processDefId, String formCode, String sysId) throws Exception {
//        String orgId = SessionHelper.getCurrentOrgId(request);
//        String deptId = SessionHelper.getCurrentDeptId(request);
//        String userId = SessionHelper.getLoginSysUserId(request);
//        SysUser loginSysUser = SessionHelper.getLoginSysUser(request);
//
//
//        Map<String, Object> parameter = new HashMap<>();
//        parameter.put("processDefId", processDefId);
//        parameter.put("formCode", formCode);
//        parameter.put("userId", userId);
//        parameter.put("deptId", deptId);
//        parameter.put("orgId", orgId);
//        parameter.put("sysId", sysId);
//        parameter.put("taskIds", taskIds);
//
//        LantopSubmit ls = new LantopSubmit();
//        ls.setOrgId(orgId);
//        ls.setDeptId(deptId);
//        ls.setSubmitTitile(loginSysUser.getName() + "的归档计划");
//        ls.setSubmitUserId(userId);
//        ls.setSubmitUserName(loginSysUser.getName());
//        ls.setSubmitDeptId(deptId);
//        ls.setSubmitDeptName(loginSysUser.getDeptName());
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH：mm：ss");
//        ls.setApplayTime(sdf.parse(sdf.format(new Date(System.currentTimeMillis()))));
//        Map<String, Object> map = new HashMap<>();
//
//        try {
//            map = archivePlanService.setTaskArchiveEnd(ls, parameter);
//            map.put("flag", PlatformConstant.OpResult.success.ordinal());
//        } catch (Exception e) {
//            map.put("flag", PlatformConstant.OpResult.failure.ordinal());
//        }
//        return map;
//    }


    /**
     * 给项目设置模板
     *
     * @param
     * @throws
     * @author xmw
     */
    @RequestMapping("/toSubmitPlanJsp")
    public String toSubmitPlanJsp(HttpServletRequest request, String id, String taskNumber) throws Exception {
        request.setAttribute("id", id);
        return "avicit/im/lantop/archiveplanmanager/archiveplanedit/ArchivePlanSubmitDetailIframe";
    }

    /**
     * 给项目设置模板
     *
     * @param
     * @throws
     * @author xmw
     */
//    @RequestMapping("/getSubmitPlanById")
//    @ResponseBody
//    public Map<String, Object> getSubmitPlanById(Integer page, Integer rows, String id, String sysId) throws Exception {
//        //根据流程送审表id获取送审的计划数据
//        Map<String, Object> lists = archivePlanService.getArchiveSubmintPlanByFlowId(page, rows, id);
//        return lists;
//    }


    /**
     * 获取提交审批项目所属计划数据
     *
     * @param request
     * @return
     * @throws Exception ModelAndView
     * @author 钟一华
     */
//    @RequestMapping("/getSubmitPlanData")
//    public ModelAndView getSubmitData(HttpServletRequest request) throws Exception {
//        ModelAndView mav = new ModelAndView();
//        mav.setView(null);
//        String id = request.getParameter("id");
//        String sysId = request.getParameter("sysId");
//        try {
//            LantopSubmit ls = this.deptdocmanagerService.getSubmitById(id);
//            String entryData = this.deptdocmanagerService.getTaskNumberById(id);
//            String[] entryDatas = entryData.split("_");
//            if (null != ls) {
//                if (null != ls.getSubmitUserId() && !"".equals(ls.getSubmitUserId())) {
//                    ls.setSubmitUserName(userLoader.getSysUserById(ls.getSubmitUserId()).getName());
//                }
//                if (null != ls.getSubmitDeptId() && !"".equals(ls.getSubmitDeptId())) {
//                    ls.setSubmitDeptName(deptLoader.getSysDeptTl(ls.getSubmitDeptId(), "zh_CN").getDeptName());
//                }
//                if (null != ls.getRcvUserId() && !"".equals(ls.getRcvUserId())) {
//                    ls.setRcvUserName(userLoader.getSysUserById(ls.getRcvUserId()).getName());
//                }
//                if (null != ls.getRcvDeptId() && !"".equals(ls.getRcvDeptId())) {
//                    ls.setRcvDeptName(deptLoader.getSysDeptTl(ls.getRcvDeptId(), "zh_CN").getDeptName());
//                }
//            }
//            // 根据归档ID查找数据归档单位名称
//            String deptName = deptdocmanagerService.getDeptNameBySubmitId(id);
//
//            //根据送审id获取送审项目所在计划
//            ArchivePlan archivePlan = archivePlanService.getPlanByFromId(id);
//
//            mav.addObject("archivePlan", archivePlan);
//            mav.addObject("deptName", deptName);
//            mav.addObject("taskNumber", entryDatas[0]);
//            mav.addObject("taskStatus", entryDatas[1]);
//            mav.addObject("id", id);
//            mav.addObject("sysId", sysId);
//            mav.addObject("ls", ls);
//            mav.addObject("flag", PlatformConstant.OpResult.success.ordinal());
//        } catch (Exception e) {
//            mav.addObject("flag", PlatformConstant.OpResult.failure.ordinal());
//            e.printStackTrace();
//        }
//        return mav;
//    }


    /**
     * 计划项目关联预归档文件
     *
     * @return
     */
//    @RequestMapping("/saveFlieRelationTask")
//    @ResponseBody
//    public Map<String, Object> saveFlieRelationTask(HttpServletRequest request, String fileNodeId, String fileIds, String taskId, String isAn) {
//        String orgId = SessionHelper.getCurrentOrgId(request);
//        String deptId = SessionHelper.getCurrentDeptId(request);
//        String queryDimension = request.getParameter("queryDimension"); //
//        String tableId = request.getParameter("tableId"); //
//        String loginName = SessionHelper.getLoginName(request);
//        loginName = loginName.toUpperCase();
//        SysUser sysUser = SessionHelper.getLoginSysUser(request);
//        String userName = sysUser.getName();
//        String userId = SessionHelper.getLoginSysUserId(request);
//        boolean isExistArchiveDept = false; // 是否存在归档部门字段
//        boolean isExistxmfzr = false; // 是否存在项目负责人字段
//        boolean isExistNodeName = false; // 当前数据节点的父类是否是技术类
//        boolean fileTabFlag = false; // 是否为文件级
//        StringBuffer searchSbSql = new StringBuffer(); // 根据维度进行拼接SQL
//        if(tableId!=null&&!tableId.equals("")){
//            String archiveDeptName = "ARCHIVE_DEPT"; // 归档部门字段名称
//            String xmfzrName = "XMFZR"; // 项目负责人字段名称
//            isExistArchiveDept = isExistColumn(archiveDeptName,tableId);
//            isExistxmfzr = isExistColumn(xmfzrName,tableId);
//        }
//        if (fileNodeId!=null&&fileNodeId!=""){
//            isExistNodeName = getParentNodeDataByNodeNameAndNodeId(fileNodeId,"技术类"); // 查询当前数据节点的父级是否有技术类
//        }
//
//        // SanXiaFiles create by zhaoxiaolong 是否为文件级表名
//        if (tableId!=null&&!"".equals(tableId)&&!"null".equals(tableId)){
//            StringBuffer sbTabSql = new StringBuffer();
//            sbTabSql.append("SELECT TABLE_NAME FROM CBB_TABLES WHERE ID='"+tableId+"'");
//            List<Map<String,Object>> tabDataList = this.jdbcAvicit.getJdbcTemplate().queryForList(sbTabSql.toString());
//            if(tabDataList!=null&&tabDataList.size()>0){
//                String tabName = tabDataList.get(0).get("TABLE_NAME").toString();
//                if (tabName.indexOf("WJJ")!=-1||tabName.indexOf("WJ")!=-1){
//                    fileTabFlag = true;
//                }
//            }
//        }
//
//        if (queryDimension!=null&&queryDimension!=""){
//            if(isExistArchiveDept||isExistxmfzr){
//                if(queryDimension.equals("1")){  // 兼职档案管理员根据归档部门是当前部门的，并且如果该数据节点是技术类下的，需要加上项目负责人是当前登录用户的过滤
//                    String currentDeptName = SessionHelper.getCurrentDeptName(request); // 当前登录部门名称
//                    if (isExistArchiveDept){
//                        searchSbSql.append(" AND ( ARCHIVE_DEPT = '"+currentDeptName+"' OR   CREATED_BY='"+userId+"' OR DEPT_ID='"+deptId+"' ) ");
//                    }else {
//                        /*mav.addObject("total", 0);
//                        mav.addObject("rows", new ArrayList<>());
//                        return mav;*/
//                    }
//                    if (isExistNodeName){ // 父级是技术类需要增加项目负责人查询SQL
//                        if(!fileTabFlag){ // 案卷需要判断项目负责人是否存在
//                            if (isExistxmfzr){
//                                if(searchSbSql!=null&&searchSbSql.toString()!=""){
//                                    searchSbSql = new StringBuffer();
//                                    searchSbSql.append(" AND ( CREATED_BY='"+userId+"' OR ARCHIVE_DEPT = '"+currentDeptName+"' OR DEPT_ID='"+deptId+"' ");
//                                    searchSbSql.append(" OR ( UPPER(XMFZR) = '"+userName+"#"+loginName+"' OR UPPER(XMFZR) = '"+userName+"("+loginName+")'  ) ) ");
//                                }else {
//                                    searchSbSql.append(" AND ( ( UPPER(XMFZR) = '"+userName+"#"+loginName+"' OR UPPER(XMFZR) = '"+userName+"("+loginName+")' )  OR   CREATED_BY='"+userId+"' ) ");
//                                }
//                            }else {
//                                // 如果没有项目负责人字段，查询创建人是自己的
//                                searchSbSql.append(" AND  CREATED_BY='"+userId+"'  ");
//                            }
//                        }
//                    }
//                }else if (queryDimension.equals("2")){
//                    if (fileTabFlag){ // 文件级，不需要校验项目负责人
//                        searchSbSql.append(" AND  CREATED_BY='"+userId+"'  ");
//                    }else {
//                        if (isExistNodeName){ // 父级是技术类需要增加项目负责人查询SQL
//                            if (isExistxmfzr){
//                                searchSbSql.append(" AND ( ( UPPER(XMFZR) = '"+userName+"#"+loginName+"' OR UPPER(XMFZR) = '"+userName+"("+loginName+")' )  OR   CREATED_BY='"+userId+"'  ) ");
//                            }else {
//                                // 如果没有项目负责人字段，查询创建人是自己的
//                                searchSbSql.append(" AND  CREATED_BY='"+userId+"'  ");
//                            }
//                        }else {
//                            // 文件级，不需要校验项目负责人
//                            searchSbSql.append(" AND  CREATED_BY='"+userId+"'  ");
//                        }
//                    }
//                }
//            }else {
//                /*mav.addObject("total", 0);
//                mav.addObject("rows", new ArrayList<>());
//                return mav;*/
//            }
//        }
//
//
//        Map<String, Object> resultMap = archivePlanService.saveFlieRelationTask(orgId, deptId, "LANTOP", fileNodeId, fileIds, taskId, isAn,searchSbSql.toString());
//        return resultMap;
//    }




    /**
     * SanXiaFiles create by zhaoxiaolong 根据当前数据节点ID查询对应父级节点是否存在
     * @param nodeId
     * @param archiveClassNodeName
     * @return
     */
    private boolean getParentNodeDataByNodeNameAndNodeId(String nodeId,String archiveClassNodeName){
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("\n" +
                "SELECT\n" +
                "\tCOUNT( 1 ) COUNT \n" +
                "FROM\n" +
                "\t( SELECT ARCHIVE_CLASS_NODE_NAME FROM LANTOP_ARCHIVE_CLASS START WITH ID = '"+nodeId+"' CONNECT BY PRIOR PARENT_ID = ID ) \n" +
                "WHERE\n" +
                "\tARCHIVE_CLASS_NODE_NAME = '"+archiveClassNodeName+"'");
        List<Map<String,Object>> countlist = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
        if(countlist!=null&&countlist.size()>0){
            int count = Integer.valueOf(countlist.get(0).get("COUNT").toString());
            if(count>0){
                return true;
            }else {
                return false;
            }
        }else {
            return false;
        }
    }


    /**
     * SanXiaFiles create by zhaoxiaolong 查询表是否存在此字段
     * @param columnName
     * @param tableId
     * @return
     */
    private boolean isExistColumn(String columnName,String tableId){
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT\n" +
                "\tCOUNT( 1 ) COUNT \n" +
                "FROM\n" +
                "\tUSER_TAB_COLUMNS \n" +
                "WHERE\n" +
                "\tTABLE_NAME = ( SELECT TABLE_NAME FROM CBB_TABLES WHERE ID = '"+tableId+"' ) \n" +
                "\tAND COLUMN_NAME = '"+columnName+"' ");
        List<Map<String,Object>> countlist = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
        if(countlist!=null&&countlist.size()>0){
            int count = Integer.valueOf(countlist.get(0).get("COUNT").toString());
            if(count>0){
                return true;
            }else {
                return false;
            }
        }else {
            return false;
        }
    }



//    @RequestMapping("/getRelationTaskArchive")
//    @ResponseBody
//    public Map<String, Object> getRelationTaskArchive(HttpServletRequest request, String taskId, String sysId) {
//        String orgId = SessionHelper.getCurrentOrgId(request);
//        String deptId = SessionHelper.getCurrentDeptId(request);
//        Map<String, Object> resultMap = archivePlanService.getRelationTaskArchive(orgId, deptId, sysId, taskId);
//        return resultMap;
//    }

    /**
     * 删除流程
     *
     * @param request
     * @return
     * @throws Exception
     */
//    @RequestMapping("/deleteSubmitData")
//    public ModelAndView deleteSubmitData(HttpServletRequest request) throws Exception {
//        ModelAndView mav = new ModelAndView();
//        String formId = request.getParameter("id");
//        try {
//            //结束主流程
//            BpmOperateService bpmOperateService = SpringFactory.getBean(BpmOperateService.class);
//            bpmOperateService.deleteProcessInstanceByFormId(formId);
//            archivePlanService.updateArchiveplan(formId);
//            mav.addObject("flag", "1");
//        } catch (Exception e) {
//            e.printStackTrace();
//            mav.addObject("flag", "0");
//        }
//        return mav;
//    }


    /**
     * 添加统计下载数接口
     *
     * @param request
     * @param fileId
     * @return
     */
//    @RequestMapping(value = "/addDownNum", method = RequestMethod.POST)
//    @ResponseBody
//    public Map<String, Object> addDownNum(HttpServletRequest request, @RequestBody Map<String, Object> map) {
//        Map<String, Object> result = new HashMap<>();
//        String paramStr = "";
//        if (map != null && map.size() > 0) {
//            paramStr = map.get("fileId").toString();
//        }
//        try {
//            if (paramStr != null && !"".equals(paramStr)) {
//                String[] split = paramStr.split(":");
//                int index = split.length;
//                String recordId = split[0];
//                String orgId = "";
//                String deptId = "";
//                String userId = "";
//                if (index > 1) {
//                    orgId = split[1];
//                }
//                if (index > 2) {
//                    deptId = split[2];
//                }
//                if (index > 3) {
//                    userId = split[3];
//                }
//                archivePlanService.createMyDownByIntfs(orgId, deptId, "LANTOP", recordId, userId, "");
//            }
//            result.put("msg", 1);
//        } catch (Exception e) {
//            result.put("msg", 0);
//            e.printStackTrace();
//        }
//        return result;
//    }


    @RequestMapping("/moveNode")
    @ResponseBody
    public Map<String, Object> moveNode(String targetNodeId, String treeId) {
        Map<String, Object> param = new HashMap<>();
        param.put("targetNodeId", targetNodeId);
        param.put("treeId", treeId);
        Map<String, Object> resultMap = archivePlanService.moveNode(param);
        return resultMap;
    }


    @RequestMapping({"/findChildsByNodeId"})
    public ModelAndView findChildsByNodeId(String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mav = new ModelAndView();
        String orgId = SessionHelper.getCurrentOrgId(request);
        String deptId = SessionHelper.getCurrentDeptId(request);
        String sysId = request.getParameter("sysId");
        Object nodes = new ArrayList();
        try {
            List<TreeNode> treeNodeList = archivePlanService.findChildsByNodeId(id);
            mav.addObject("data", treeNodeList);

            mav.addObject("result", PlatformConstant.OpResult.success.ordinal());
        } catch (Exception var11) {
            mav.addObject("result", PlatformConstant.OpResult.failure.ordinal());
            mav.addObject("msg", "后台处理异常, " + var11.getMessage());
        }
        return mav;
    }
}
